package net.wsnetwork.jawa.frontend;

import java.net.MalformedURLException;
import java.rmi.AccessException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import net.wsnetwork.jawa.common.Constants;
import net.wsnetwork.jawa.master.BackendInfo;
import net.wsnetwork.jawa.master.MasterInterface;

public class MasterClient {
    private static final Logger LOG = Logger.getLogger(MasterClient.class.getCanonicalName());

    private final MasterInterface master;
    private List<BackendInfo> backends = new ArrayList<BackendInfo>();
    private Thread heartbeatThread;

    public MasterClient(String remoteHost) throws
    AccessException, RemoteException, NotBoundException, MalformedURLException {
        master = (MasterInterface) Naming.lookup(
                "//" + remoteHost + "/" + Constants.MASTER_SERVICE_NAME);
    }

    public void start() {
        Thread heartbeatThread = new Thread(new HeartbeatRunnable());
        heartbeatThread.start();
    }

    public void stop() {
        heartbeatThread.interrupt();
    }

    public List<BackendInfo> getBackends() {
        synchronized (backends) {
            return backends;
        }
    }

    private class HeartbeatRunnable implements Runnable {
        @Override public void run() {
            while (true) {
                List<BackendInfo> newBackends = null;
                try {
                    newBackends = master.GetBackends();
                } catch (RemoteException e) {
                    LOG.warning("Unable to send heartbeat: " + e);
                }

                if (newBackends != null && newBackends.size() > 0) {
                    synchronized (backends) {
                        backends = newBackends;
                    }
                }

                try {
                    Thread.sleep(Constants.HEARTBEAT_INTERVAL);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    }
}
